use regex::Regex;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum VersionStability {
    Alpha,
    Beta,
    Stable,
}

#[derive(Debug, Clone)]
struct CrdVersion {
    major: u32,
    minor: Option<u32>,
    stability: VersionStability,
    stability_version: Option<u32>,
    #[allow(dead_code)]
    original: String,
}

// 复制版本解析函数进行测试
fn parse_version(version_str: &str) -> Result<CrdVersion, String> {
    let re = Regex::new(r"^v(\d+)(?:\.(\d+))?(?:(alpha|beta)(\d+)?)?$")
        .map_err(|e| format!("正则表达式错误: {}", e))?;
    
    if let Some(captures) = re.captures(version_str) {
        let major = captures.get(1)
            .unwrap()
            .as_str()
            .parse::<u32>()
            .map_err(|e| format!("解析主版本号失败: {}", e))?;
        
        let minor = captures.get(2)
            .map(|m| m.as_str().parse::<u32>())
            .transpose()
            .map_err(|e| format!("解析次版本号失败: {}", e))?;
        
        let (stability, stability_version) = match captures.get(3) {
            Some(stability_match) => {
                let stability = match stability_match.as_str() {
                    "alpha" => VersionStability::Alpha,
                    "beta" => VersionStability::Beta,
                    _ => return Err(format!("未知的稳定性标识: {}", stability_match.as_str())),
                };
                
                let stability_version = captures.get(4)
                    .map(|m| m.as_str().parse::<u32>())
                    .transpose()
                    .map_err(|e| format!("解析稳定性版本号失败: {}", e))?;
                
                (stability, stability_version)
            }
            None => (VersionStability::Stable, None),
        };
        
        Ok(CrdVersion {
            major,
            minor,
            stability,
            stability_version,
            original: version_str.to_string(),
        })
    } else {
        Err(format!("无效的版本格式: {}", version_str))
    }
}

// 复制版本比较函数进行测试
fn compare_versions(a: &CrdVersion, b: &CrdVersion) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    
    // 首先比较主版本号
    match a.major.cmp(&b.major) {
        Ordering::Equal => {}
        other => return other,
    }
    
    // 比较次版本号
    match (a.minor, b.minor) {
        (Some(a_minor), Some(b_minor)) => {
            match a_minor.cmp(&b_minor) {
                Ordering::Equal => {}
                other => return other,
            }
        }
        (Some(_), None) => return Ordering::Greater,
        (None, Some(_)) => return Ordering::Less,
        (None, None) => {}
    }
    
    // 比较稳定性级别 (Stable > Beta > Alpha)
    match a.stability.cmp(&b.stability) {
        Ordering::Equal => {}
        other => return other,
    }
    
    // 比较稳定性版本号
    match (a.stability_version, b.stability_version) {
        (Some(a_stab), Some(b_stab)) => a_stab.cmp(&b_stab),
        (Some(_), None) => Ordering::Greater,
        (None, Some(_)) => Ordering::Less,
        (None, None) => std::cmp::Ordering::Equal,
    }
}

// 复制最新版本选择函数进行测试
fn select_latest_version(versions: &[serde_yaml::Value]) -> Option<&serde_yaml::Value> {
    let mut best_version: Option<(&serde_yaml::Value, CrdVersion)> = None;
    
    for version in versions {
        if let Some(name) = version.get("name").and_then(|n| n.as_str()) {
            if let Ok(parsed_version) = parse_version(name) {
                match &best_version {
                    None => {
                        best_version = Some((version, parsed_version));
                    }
                    Some((_, current_best)) => {
                        if compare_versions(&parsed_version, current_best) == std::cmp::Ordering::Greater {
                            best_version = Some((version, parsed_version));
                        }
                    }
                }
            }
        }
    }
    
    best_version.map(|(version, _)| version)
}

#[test]
fn test_version_parsing() {
    // 测试版本解析
    let test_cases = vec![
        ("v1", Ok((1, None, VersionStability::Stable, None))),
        ("v2", Ok((2, None, VersionStability::Stable, None))),
        ("v1beta1", Ok((1, None, VersionStability::Beta, Some(1)))),
        ("v1alpha2", Ok((1, None, VersionStability::Alpha, Some(2)))),
        ("v2beta1", Ok((2, None, VersionStability::Beta, Some(1)))),
        ("invalid", Err("无效的版本格式")),
    ];

    for (version_str, expected) in test_cases {
        let result = parse_version(version_str);
        match (result, expected) {
            (Ok(parsed), Ok((major, minor, stability, stab_ver))) => {
                assert_eq!(parsed.major, major);
                assert_eq!(parsed.minor, minor);
                assert_eq!(parsed.stability, stability);
                assert_eq!(parsed.stability_version, stab_ver);
                println!("✓ {} -> {:?}", version_str, parsed);
            }
            (Err(_), Err(_)) => {
                println!("✓ {} correctly failed to parse", version_str);
            }
            (result, expected) => {
                panic!("测试失败: {} -> result: {:?}, expected: {:?}", version_str, result, expected);
            }
        }
    }
}

#[test]
fn test_version_comparison() {
    // 测试版本比较
    let test_cases = vec![
        ("v2", "v1", std::cmp::Ordering::Greater), // v2 > v1
        ("v1", "v1beta1", std::cmp::Ordering::Greater), // v1 > v1beta1
        ("v1beta1", "v1alpha2", std::cmp::Ordering::Greater), // v1beta1 > v1alpha2
        ("v1alpha2", "v1alpha1", std::cmp::Ordering::Greater), // v1alpha2 > v1alpha1
        ("v1", "v1", std::cmp::Ordering::Equal), // v1 == v1
    ];

    for (a_str, b_str, expected) in test_cases {
        let a = parse_version(a_str).unwrap();
        let b = parse_version(b_str).unwrap();
        let result = compare_versions(&a, &b);
        assert_eq!(result, expected, "比较 {} vs {} 失败", a_str, b_str);
        println!("✓ {} vs {} -> {:?}", a_str, b_str, result);
    }
}

#[test]
fn test_select_latest_version() {
    // 创建测试用的版本数据
    let versions_yaml = r#"
- name: v1alpha1
  served: true
  storage: false
- name: v1beta1
  served: true
  storage: false
- name: v1
  served: true
  storage: true
- name: v2beta1
  served: true
  storage: false
"#;
    
    let versions: Vec<serde_yaml::Value> = serde_yaml::from_str(versions_yaml).unwrap();
    let latest = select_latest_version(&versions);
    
    assert!(latest.is_some());
    let latest_name = latest.unwrap().get("name").unwrap().as_str().unwrap();
    assert_eq!(latest_name, "v2beta1", "应该选择v2beta1作为最新版本");
    println!("✓ 从版本列表中选择了最新版本: {}", latest_name);
} 